import json
import time
from pyquery import PyQuery as pq
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys

# 创建webdriver对象
browser = webdriver.Firefox()
# 等待变量
wait = WebDriverWait(browser, 10)

# 获取商品信息
def getProduct():
    time.sleep(5)

    wait.until(
        EC.presence_of_element_located(
            (By.CLASS_NAME, 'Card--doubleCardWrapper--L2XFE73')
        )
    )
    html = browser.page_source
    doc = pq(html)
    # 获取当前页面所有商品信息的html源码
    items = doc('.Card--doubleCardWrapper--L2XFE73').items()
    for item in items:
        # print("-------------------------------", item)
        product = {
            'image': item.find('img').attr('src')
        }
        print(product)


def taobaoSearch():
    # 搜索动作
    try:
        # 打开淘宝首页
        browser.get("https://www.taobao.com/")
        # 等待搜索框加载完成
        search_input = wait.until(EC.presence_of_element_located(
            (By.CSS_SELECTOR, '#q')
        ))

        # 输入框中传入搜索内容
        search_input.send_keys('iphone')
        time.sleep(2)
        # 点击搜索
        search_input.send_keys(Keys.ENTER)
    except TimeoutError:
        print("网站打开错误")

def modelLogin():
    # 模拟登陆
    # 打开淘宝首页
    browser.get("https://www.taobao.com/")
    browser.delete_all_cookies()
    with open('cookies_tao.json', 'r', encoding='utf-8') as f:
        listCookies = json.loads(f.read())
    # print(listCookies)
    for cookie in listCookies:
        browser.add_cookie(
            {
                'domain': cookie['domain'],
                'name': cookie['name'],
                'value': cookie['value'],
                'path': '/',
                'expires': None
            }
        )

if __name__ == '__main__':
    modelLogin()
    taobaoSearch()
    getProduct()